package cn.itcast.wushangxiantu.BaseAdapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import cn.itcast.wushangxiantu.Activity.ChouJiang;
import cn.itcast.wushangxiantu.Activity.Login;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.UserData.UserBag;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChouJiangDaoJuGiveViewAdapter extends BaseAdapter {
    private Context context;
    private UserBag.BeibaoBean daojuBean;
    int num = 0;
    User user;

    public UserBag.BeibaoBean getDaojuBean() {
        return daojuBean;
    }

    public ChouJiangDaoJuGiveViewAdapter(Context context) {
        this.context = context;
    }

    public void setDaojuBean(UserBag.BeibaoBean daojuBean) {
        this.daojuBean = daojuBean;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return daojuBean.getDaoju().size();
    }

    @Override
    public Object getItem(int i) {
        return daojuBean.getDaoju().get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        view = View.inflate(context, R.layout.griveview_bag, null);
       ViewHolder viewHolder=new ViewHolder(view);
       viewHolder.tvName.setText(daojuBean.getDaoju().get(i).getWpname());
       viewHolder.tvNumber.setText(daojuBean.getDaoju().get(i).getWpnumber()+"");
        if (daojuBean.getDaoju().get(i).getWpid()<=4){
            viewHolder.tvName.setTextColor(ContextCompat.getColor(context,R.color.buyu));
        }else if (daojuBean.getDaoju().get(i).getWpid()<=8){
            viewHolder.tvName.setTextColor(ContextCompat.getColor(context,R.color.kuangqu));
        }else if (daojuBean.getDaoju().get(i).getWpid()<=12){
            viewHolder.tvName.setTextColor(ContextCompat.getColor(context,R.color.linqu));
        }else if (daojuBean.getDaoju().get(i).getWpid()<=16){
            viewHolder.tvName.setTextColor(ContextCompat.getColor(context,R.color.caiji));
        }else if (daojuBean.getDaoju().get(i).getWpid()==27){
            viewHolder.tvName.setTextColor(ContextCompat.getColor(context,R.color.lingshi5));
        }else if (daojuBean.getDaoju().get(i).getWpid()<=26){
            viewHolder.tvName.setTextColor(ContextCompat.getColor(context,R.color.lingshi6));
        }else {

        }
       viewHolder.tvName.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               GeneralDialogDaoJu("消耗道具","本次倍数为"+ ChouJiang.number+"倍数\n预计消耗：\n产物"
                       +ChouJiang.number*5+"\n其余"+ChouJiang.number*30+
                       "\n当前选择为:"+daojuBean.getDaoju().get(i).getWpname()+"\n拥有数量为:"+daojuBean.getDaoju().get(i).getWpnumber(),i);
               num=i;
           }
       });
        return view;
    }
    public void GeneralDialogDaoJu(String head, String content, final int num) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(head)

                .setMessage(content)
                .setNegativeButton("抽一次", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                            if (num<0){

                            }else{
                                //开始抽奖发送请求
                                getChouJiang(ChouJiang.number,daojuBean.getDaoju().get(num).getBag_id(),ChouJiangGiveViewAdapter.num);
                            }
                    }
                })
                .setNeutralButton("十连抽（九折）", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (num<0){

                        }else{
                            //开始抽奖发送请求
                            getTenChouJiang(ChouJiang.number,daojuBean.getDaoju().get(num).getBag_id(),ChouJiangGiveViewAdapter.num);
                        }
                    }
                });
        dialog = builder.create();
        dialog.show();
    }
    public void GeneralDialogDaoJu(String head, String content) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(head)

                .setMessage(content)
                .setNegativeButton("抽一次", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                            //开始抽奖发送请求
                            getChouJiang(ChouJiang.number,daojuBean.getDaoju().get(num).getBag_id(),ChouJiangGiveViewAdapter.num);
                    }
                })
                .setNeutralButton("十连抽（九折）", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (num<0){

                        }else{
                            //开始抽奖发送请求
                            getTenChouJiang(ChouJiang.number,daojuBean.getDaoju().get(num).getBag_id(),ChouJiangGiveViewAdapter.num);
                        }
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    /**
     *
     * @param number 倍数
     * @param bag_id 背包id
     * @param num 地区
     */
    private void getChouJiang(int number, int bag_id,int num) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userName=" + Login.getUser().getUsernumber() + "&need=choujiang" +
                "&bag_id=" + bag_id + "&number=" + number + "&num=" + num, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("choujiang1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("choujiang2", src);
                User user =null;
                try {
                    user = new Gson().fromJson(src, User.class);
                }catch (Exception e){

                }
                Message message = new Message();
                message.obj = user;
                message.what = 1;
                handler.sendMessage(message);
            }
        });
    }
    /**
     *
     * @param number 倍数
     * @param bag_id 背包id
     * @param num 地区
     */
    private void getTenChouJiang(int number, int bag_id,int num) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userName=" + Login.getUser().getUsernumber() + "&need=tenchoujiang" +
                "&bag_id=" + bag_id + "&number=" + number + "&num=" + num, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("choujiang1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("choujiang2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                }catch (Exception e){

                }
                Message message = new Message();
                message.obj = user;
                message.what = 1;
                handler.sendMessage(message);
            }
        });
    }
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            switch (message.what){
                case 1:
                    User user= (User) message.obj;
                    if (user!=null){
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        GeneralDialogDaoJu("抽奖详情",user.getStw());
                        if (user.getMoney()!=0){
                            //从服务器获取的值默认是+1的
                            if (user.getMoney()==1){
                                daojuBean.getDaoju().remove(num);
                            }else{
                                daojuBean.getDaoju().get(num).setWpnumber((user.getMoney()-1));
                            }
                            notifyDataSetChanged();
                        }
                    }else{
                        ToastUtil.toast(context,"服务器炸了");
                    }
                    break;
                case 2:

                    break;
            }
            EventBus.getDefault().post(new MessageEvent("DaoJu"));
            return false;
        }
    });
    class ViewHolder {
        public View rootView;
        public TextView tvName;
        public TextView tvNumber;
        public RelativeLayout li;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.tvName = (TextView) rootView.findViewById(R.id.tvName);
            this.tvNumber = (TextView) rootView.findViewById(R.id.tvNumber);
            this.li = (RelativeLayout) rootView.findViewById(R.id.li);
        }

    }
}
